package com.ruoyi.app.controller.order.controller;

import com.ruoyi.app.controller.order.service.IShopPetrolOrderService;
import com.ruoyi.app.controller.pay.service.IPayService;
import com.ruoyi.app.controller.shop.service.IShopAppletService;
import com.ruoyi.app.framework.base.BaseAppController;
import com.ruoyi.common.annotation.AuthMember;
import com.ruoyi.common.constant.OrderConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.entity.DO.member.MemberDO;
import com.ruoyi.common.entity.DO.order.ShopPetrolOrderDO;
import com.ruoyi.common.entity.DO.shop.ShopAppletDO;
import com.ruoyi.common.entity.VO.PayVO;
import com.ruoyi.common.entity.VO.order.ShopOrderSearchVO;
import com.ruoyi.common.entity.wxpay.WxConfig;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/petrolOrder")
@Api(value = "加油订单", description = "加油订单模块接口")
public class PetrolOrderController extends BaseAppController {

    @Resource
    private IShopAppletService shopAppletService;

    @Resource
    private IShopPetrolOrderService shopPetrolOrderService;

    @Resource
    private IPayService payService;

    /**
     * 确认加油订单
     */
    @PostMapping("/confirm")
    public AjaxResult confirm(@AuthMember MemberDO member, @RequestBody ShopPetrolOrderDO shopPetrolOrderDO) {
        if (null == shopPetrolOrderDO.getProductId() || 0L == shopPetrolOrderDO.getProductId()) {
            throw new BusinessException("请先选择油号！");
        }
        if (null == shopPetrolOrderDO.getOrderCost() || BigDecimal.ZERO.equals(shopPetrolOrderDO.getOrderCost())) {
            throw new BusinessException("请输入加油金额！");
        }
        if (null == shopPetrolOrderDO.getProductAttrId()) {
            shopPetrolOrderDO.setProductAttrId(0L);
        }
        shopPetrolOrderDO.setShopId(member.getShopId());
        shopPetrolOrderDO.setMemberId(member.getId());
        //TODO：删除之前未支付的订单
//        shopPetrolOrderService.deleteByMemberId(member.getId());
        if (null != shopPetrolOrderDO.getPayWay()
                && OrderConstants.OrderPayWayEnum.match(shopPetrolOrderDO.getPayWay()).getValue() == -1) {
            return error("不支持所选支付方式！");
        }
        return AjaxResult.success(shopPetrolOrderService.confirm(shopPetrolOrderDO, false));
    }

    /**
     * 创建加油订单
     */
    @PostMapping("/create")
    public AjaxResult create(@AuthMember MemberDO member, @RequestBody ShopPetrolOrderDO orderCreateDO) {
        orderCreateDO.setMemberId(member.getId());
        orderCreateDO.setShopId(member.getShopId());
        if (null == orderCreateDO.getPayWay()) {
            return error("请选择支付方式！");
        }
        if (OrderConstants.OrderPayWayEnum.match(orderCreateDO.getPayWay()).getValue() == -1) {
            return error("不支持所选支付方式！");
        }
        return AjaxResult.success("创建订单成功", shopPetrolOrderService.create(orderCreateDO));
    }

    @ApiOperation(value = "获取订单详情", notes = "获取订单详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", required = false, paramType = "query"),
    })
    @GetMapping("/detail")
    public AjaxResult detail(@AuthMember MemberDO member) {
        ShopOrderSearchVO shopOrderSearchVO = new ShopOrderSearchVO();
        shopOrderSearchVO.setMemberId(member.getId());
        if (StringUtils.isNotEmpty(ServletUtils.getParameter("orderSn"))) {
            shopOrderSearchVO.setOrderSn(ServletUtils.getParameter("orderSn"));
        } else {
            return error("订单号缺失");
        }
        return AjaxResult.success(shopPetrolOrderService.getDetail(shopOrderSearchVO));
    }

    @ApiOperation(value = "订单支付", notes = "订单支付")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, paramType = "header"),
            @ApiImplicitParam(name = "payWay", value = "支付方式（0余额支付 2微信支付 3线下支付）", required = true, paramType = "body"),
            @ApiImplicitParam(name = "orderSn", value = "订单号", required = false, paramType = "body"),
    })
    @PostMapping("/pay")
    public AjaxResult pay(@AuthMember MemberDO member, @Valid @RequestBody PayVO payVO, BindingResult results) {
        if (results.hasErrors()) {
            return error(results.getFieldError().getDefaultMessage());
        }
        PayVO payInfo = shopPetrolOrderService.getPayInfo(payVO.getOrderSn());
        if(null == payInfo){
            throw new BusinessException("支付失败，订单创建异常！");
        }
        if (OrderConstants.OrderPayWayEnum.WX_PAY.getValue() == payInfo.getPayWay()
                && payVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()) {
            throw new BusinessException("此油品不支持余额支付！");
        }
        if (payVO.getPayWay() == OrderConstants.OrderPayWayEnum.BALANCE_PAY.getValue()) {
            //余额支付
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("shopId", member.getShopId().toString());
            notifyMap.put("memberId", member.getId().toString());
            notifyMap.put("paySn", payInfo.getPaySn());
            notifyMap.put("orderSn", payInfo.getPaySn());
            notifyMap.put("balanceAmount", payInfo.getPayCost().toString());
            shopPetrolOrderService.payNotifyHandle(notifyMap);
            return AjaxResult.success("余额支付成功！");
        } else if (payVO.getPayWay() == OrderConstants.OrderPayWayEnum.OFFLINE_PAY.getValue()) {
            //线下支付
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("shopId", member.getShopId().toString());
            notifyMap.put("memberId", member.getId().toString());
            notifyMap.put("paySn", payInfo.getPaySn());
            notifyMap.put("orderSn", payInfo.getPaySn());
            notifyMap.put("offlinePayAmount", payInfo.getPayCost().toString());
            shopPetrolOrderService.payNotifyHandle(notifyMap);
            return AjaxResult.success("线下支付成功！");
        } else {
            //TODO：查询店铺的appId和secret
            ShopAppletDO shopApplet = shopAppletService.getDetailByShopId(member.getShopId());
            if (shopApplet == null || shopApplet.getIsEnable() == null || shopApplet.getIsDelete() == 1) {
                throw new BusinessException("请联系运营平台重新开通小程序！");
            }
            if (shopApplet.getIsEnable() == 0) {
                throw new BusinessException("请联系运营平台重新上架小程序！");
            }
            //TODO：创建支付实体
            WxConfig wxConfig = new WxConfig();
            wxConfig.setAppID(shopApplet.getAppletAppId());
            wxConfig.setKey(shopApplet.getAppletPayKey());
            wxConfig.setMchID(shopApplet.getAppletMchId());
            try {
                wxConfig.setCertData(shopApplet.getShopId());
            } catch (Exception e) {
                error("支付证书错误！");
            }
            payInfo.setOpenid(member.getOpenid());
            payInfo.setWxConfig(wxConfig);
            Map result = payService.petrolOrderPay(payInfo);
            return AjaxResult.success(result);
        }
    }
}
